package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.mini.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.config.properties.WeChatProperties;
import com.ruoyi.system.domain.MyUser;
import com.ruoyi.system.mapper.MyUserMapper;
import com.ruoyi.system.service.IMyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class MyUserServiceImpl extends ServiceImpl<MyUserMapper, MyUser> implements IMyUserService {
    //微信服务接口地址
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private MyUserMapper userMapper;

    /**
     * 用户登录
     * @param code
     * @return
     */
    public MyUser login(String code) {
        String openid = getOpenid(code);

        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid==null){
            throw new ServiceException(UserConstants.OPENID_NULL);
        }

        //判断当前用户是否为新用户
        LambdaQueryWrapper<MyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MyUser::getOpenid,openid);
        MyUser user = userMapper.selectOne(wrapper);

        //如果是新用户，自动完成注册
        if(user==null){
            user = new MyUser();
            user.setOpenid(openid);
            user.setNickname(UserConstants.getNICKNAME());
            user.setHeadimg(UserConstants.getAVATAR());
            userMapper.insert(user);
        }

        //返回这个用户对象
        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //调用微信接口服务，获得当前微信用户的openid
        String url=WX_LOGIN
                +"?appid="+weChatProperties.getAppid()
                +"&secret="+weChatProperties.getSecret()
                +"&js_code="+code
                +"&grant_type=authorization_code";
        String json = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
